import { Component, OnInit, OnDestroy } from '@angular/core'
import { NzMessageService } from 'ng-zorro-antd'
import { Router, ActivatedRoute } from '@angular/router'
import { PageService } from '@shared/services/page.service'
import { INewPageColumn } from '@shared/interfaces/common'
import { ComWindow } from '@shared/classes/ComWindowClass'
import { RiskNewTabBaseComponent } from './tab-base/tab-base.component'
import { RiskNewTabConfigComponent } from './tab-config/tab-config.component'
import { RiskService } from '../risk.service'
import { RiskStoreService } from './risk-store.service'
import { I18NService } from '@core'
import { SuccessCode, ErrorCode } from '@shared/interfaces/common'

@Component({
  selector: 'app-risk-new',
  templateUrl: './new.component.html',
})
export class RiskNewComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  constructor(
    public msgSrv: NzMessageService,
    public router: Router,
    public route: ActivatedRoute,
    public pageService: PageService,
    private riskService: RiskService,
    private riskStore: RiskStoreService,
    private i18n: I18NService,
  ) {}

  ngOnInit() {
    this.initColumns()
  }

  ngOnDestroy() {
    this.riskStore.reset()
  }

  initColumns(): void {
    this.pages = [
      {
        component: new ComWindow(RiskNewTabBaseComponent, { title: 'RISK_CTRL.DETAIL.TITLE' }),
      },
    ]
  }

  submit(): void {
    const riskScheme = this.riskStore.value
    this.riskService
      .create(riskScheme)
      .subscribe(this.handleCreateSuccess.bind(this), this.handleCreateFail.bind(this))
  }

  private handleCreateSuccess(res): void {
    this.pageService.triggerGuardAlive(false)
    const { code, msg } = res
    if (!code) {
      this.msgSrv.error(this.trans('GENERAL.NOTIFICATION.CREATE_FAIL'))
      return
    }
    switch (code) {
      case SuccessCode.SUCCESS_AUDITING:
        this.msgSrv.success(this.trans('GENERAL.NOTIFICATION.SUCCESS_AUDITING'))
        break
      case SuccessCode.SUCCESS:
        this.msgSrv.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
        break
      default:
        this.msgSrv.error(`${this.i18n.fanyi(`${msg}`)}`)
    }
    this.router.navigate(['../'], { relativeTo: this.route })
  }

  private handleCreateFail(): void {
    this.msgSrv.error(this.trans('GENERAL.NOTIFICATION.CREATE_FAIL'))
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
